/*
 * @(#)Segmenter.java	1.0 10/01/07
 *
 * Copyright 2007 Fabio Gasparetti. All rights reserved.
 */

package org.tabularium.text.nlp;

import java.util.*;

import org.tabularium.text.nlp.*;

/**
 * Splits input text into semantically coherent segmentes.
 * 
 * @author Fabio Gasparetti
 * @version 1.0, 10/01/07
 */
public abstract class Segmenter {
	public static final int DEFAULT_NUMBER_SEGMENTS = -1;

	protected int numSegments = DEFAULT_NUMBER_SEGMENTS;

	/**
	 * Returns a sequence of integer that points strings that represent the
	 * segmentation of the input text in different topics.
	 */
	public abstract int[] segment(String[] sentences);

	/**
	 * Segments the input list of tags representing a given text. Returns a list
	 * of indexes that point to the first sentence tag that starts a new new
	 * segment/topic.
	 */
	public abstract int[] segment(Tag[] tags);

	/**
	 * Some segmenters might provide the chance to select the number of output
	 * segments.
	 * <p>
	 * Setting the value to -1 means that the segmenter chooses the number of
	 * segments on its own.
	 */
	public void setNumberSegments(int n) {
		numSegments = n;
	}

	/**
	 * Splits a given text into sentences using a text tagger.
	 */
	public static String[] split(TextTagger tagger, String text) {
		Tag[] tags = null;
		try {
			tags = tagger.tag(text);
		} catch (Exception ex) {
			return null;
		}
		Tag[] sentenceTags = TextTagger.filter(tags, "Sentence");
		String s;
		ArrayList tokens;
		ArrayList sentences = new ArrayList();
		for (int i = 0; i < sentenceTags.length; i++) {
			s = sentenceTags[i].getContent();
			sentences.add(s);
		}
		return (String[]) sentences.toArray(new String[] {});
	}

	/**
	 * Merges the input lines according to the segmentation indexes in the given
	 * int array.
	 */
	public static String[] segmentByIndexes(int[] idxs, String[] lines) {
		int j = 0;
		ArrayList out = new ArrayList();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < lines.length; i++) {
			if (j < idxs.length && i == idxs[j]) {
				out.add(sb.toString());
				j++;
				sb = new StringBuffer();
			}
			sb.append(lines[i] + " ");
		}
		if (sb.length() > 0)
			out.add(sb.toString());
		return (String[]) out.toArray(new String[] {});
	}
}
